package com.xmut.xmutbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmut.xmutbackend.entity.Emp;
import com.xmut.xmutbackend.entity.Result;
import com.xmut.xmutbackend.entity.Student;
import com.xmut.xmutbackend.service.IClassService;
import com.xmut.xmutbackend.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    @Autowired
    private IClassService classService;

    // 分页查询所有学员
    @GetMapping
    public Result<Page<Student>> getStudents(
            @RequestParam(required = false) String no,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) Long classId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(StringUtils.hasText(no), Student::getStudentNo, no);
        queryWrapper.like(StringUtils.hasText(name), Student::getName, name);
        queryWrapper.like(StringUtils.hasText(province), Student::getProvince, province);
        queryWrapper.eq(classId != null, Student::getClassId, classId);

        Page<Student> studentPage = studentService.page(new Page<>(page, size), queryWrapper);
        return Result.success(studentPage);
    }

    // 根据ID获取学员信息
    @GetMapping("/{id}")
    public Result<Student> getStudentById(@PathVariable Long id) {
        Student student = studentService.getById(id);
        if (student != null) {
            return Result.success(student);
        } else {
            return Result.fail("未找到对应学员");
        }
    }

    // 添加新学员（加入唯一性检查）
    @PostMapping
    public Result<Student> addStudent(@RequestBody Student student) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_no", student.getStudentNo());
        Student existingStudent = studentService.getOne(queryWrapper);
        if (existingStudent != null) {
            return Result.fail("学号已存在，添加失败");
        }

        boolean saved = studentService.save(student);
        if (saved) {
            return Result.success(student);
        } else {
            return Result.fail("添加失败");
        }
    }

    // 更新学员信息（检查班级是否存在）
    @PutMapping
    public Result<Student> updateStudent(@RequestBody Student student) {
        Long classId = student.getClassId();
        if (classId != null) {
            boolean classExists = classService.getById(classId) != null;
            if (!classExists) {
                return Result.fail("班级ID不存在，更新失败");
            }
        }
        boolean updated = studentService.updateById(student);
        if (updated) {
            return Result.success(student);
        } else {
            return Result.fail("更新失败");
        }
    }

    // 删除学员
    @DeleteMapping("/{id}")
    public Result<String> deleteStudent(@PathVariable String id) {
        // 分割字符串，转换成 List<Integer>
        List<Integer> idList = Arrays.stream(id.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        boolean removed = studentService.removeByIds(idList); // 使用 removeByIds 批量删除
        if (removed) {
            return Result.success("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }

    // 根据班级ID查询学员
    @GetMapping("/class/{classId}")
    public Result<List<Student>> getStudentsByClassId(@PathVariable Long classId) {
        List<Student> students = studentService.list(new QueryWrapper<Student>().eq("class_id", classId));
        return Result.success(students);
    }
}
